package com.qf.lanzhou.shop.api.service.impl;

import com.qf.lanzhou.shop.pojo.entity.ShopCart;
import com.qf.lanzhou.shop.api.dao.ShopCartMapper;
import com.qf.lanzhou.shop.api.service.ShopCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 是柠檬甜
 * @date 2021/1/8 16:07
 */
@Service
public class ShopCartServiceImpl implements ShopCartService {
    @Autowired
    private ShopCartMapper shopCartMapper;

    @Override
    public List<ShopCart> selectAll(ShopCart shopCart) {
        shopCart.setGoodsStatus(1);
        List list = shopCartMapper.selectByUserId(shopCart);
        return list;
    }

    @Override
    public String updateStatus(ShopCart shopCart) {
        int i = shopCartMapper.update(shopCart);
        if (i == 0) {
            throw new RuntimeException("系统繁忙，请稍后再试");
        }
        return "删除成功";
    }

    @Override
    public int updateGoodsNum(ShopCart shopCart) {
        int i = shopCartMapper.updateById(shopCart);
        if (i == 0) {
            throw new RuntimeException("太快了，慢一点。");
        }
        return i;
    }

    @Override
    public int addGoods(ShopCart shopCart) {
        List<ShopCart> shopCarts = shopCartMapper.selectByUserId(shopCart);
        //判断该用户商品是否已添加，
        System.out.println("shop+++"+shopCarts.size());
        if (shopCarts.size() != 0) {
            for (ShopCart shopCartUpdate : shopCarts) {
                //若已添加且未删除只更新商品数量
                if (shopCartUpdate.getGoodsStatus() == 1) {
                    Long goodsNum = shopCartUpdate.getGoodsNum() + shopCart.getGoodsNum();
                    shopCartUpdate.setGoodsNum(goodsNum);
                    int result = shopCartMapper.updateById(shopCartUpdate);
                    return result;
                }
                //若已添加并删除只更新商品数量
                if (shopCartUpdate.getGoodsStatus() == 0) {
                    shopCartUpdate.setGoodsStatus(1);
                    shopCartUpdate.setGoodsNum(shopCart.getGoodsNum());
                    int result = shopCartMapper.updateById(shopCartUpdate);
                    return result;
                }
            }
        }
        //该用户商品未添加，插入
        int insert = shopCartMapper.insert(shopCart);
        if (insert == 0) {
            throw new RuntimeException("系统繁忙，请稍后再试");
        }
        return insert;
    }

}
